#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice, IceGrid, IceStorm
import os, sys, datetime, time

SLICE = os.path.join('..', 'slice')
FILE1 = os.path.join(SLICE, 'Oculus.ice')
Ice.loadSlice('--all -I/usr/share/slice', ['-I' + SLICE, FILE1])

TOPIC = 'VIDEO'
CAMERA = 4
SCENE = 'roundabout'
LOG_EVENT = 'client_notification'
EVENTS_SECOND = 25.0

try:
    EVENTS = int(sys.argv[1])
except IndexError:
    EVENTS = 1

import Oculus

class AMI_Model_notifyI (object):

    def ice_response (self):
        pass

    def ice_exception (self, ex):
        pass

class Client (Ice.Application):

    def run (self, argv):

        query = IceGrid.QueryPrx.checkedCast(self.communicator().stringToProxy("IceGrid/Query"))

        manager = IceStorm.TopicManagerPrx.checkedCast(query.findObjectById(self.communicator().stringToIdentity('Oculus.IceStorm/TopicManager')))

        try:
	    topic = manager.retrieve(TOPIC)
            print 'VIDEO topic retrieved!'
        except IceStorm.NoSuchTopic:
            topic = manager.create(TOPIC);
            print 'VIDEO topic created!'

        publisher = topic.getPublisher()
        prx = Oculus.PAPrx.uncheckedCast(publisher)

        prx = Oculus.PAPrx.checkedCast(query.findObjectById(self.communicator().stringToIdentity('pa')))
        prx = prx.ice_connectionCached(False)

        prx.clean()

        sniffer = Oculus.SnifferPrx.checkedCast(query.findObjectById(self.communicator().stringToIdentity('sniffer')))

        f = open(os.path.join('..', 'scenes', SCENE, 'salida.txt'), 'r+')

        c = 0

        ti = datetime.datetime.today()

        for l in f:

            aux = l.split(':')
            frame = int(aux[0])

            actors = []

            for obj in aux[1:]:

                ev = obj.split(';')

                obj_id = ev[0]
                pos = Oculus.Position(int(ev[1]), int(ev[2]))
                w, h = int(ev[3]), int(ev[4])
                hs, vs = int(ev[5]), int(ev[6])

                aux = ev[7].split('\n')[0]
                a, b = aux.split(',')
                mov = float(a) + float('0.' + b)

                actor = Oculus.Actor(obj_id, pos, w, h, hs, vs, mov)
                actors.append(actor)

            f = Oculus.Frame(frame, actors)
            event = Oculus.VideoEvent(CAMERA, [f])

            time.sleep(float(0.95 / EVENTS_SECOND))

            sniffer.notify(CAMERA, frame, LOG_EVENT, 0.0)
            prx.notify_async(AMI_Model_notifyI(), event)

            c += 1
            if c == EVENTS:
                break

        tf = datetime.datetime.today()
        print 'Time: ' + str(tf - ti)

        return 0

Client().main(sys.argv, os.path.join('..', 'config', 'config.locator'))
